package com.yantong.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * 
 * Title: DateUtil<br/>
 * Description: 日期处理工具类<br/>
 * Company: cloudfn<br/>
 * 
 * 
 * 
 */
public class DateUtil {
    /**
     * 时间单位
     */
    public static final String YEAR = "YEAR";
    public static final String MONTH = "MONTH";
    public static final String DAY = "DAY";
    public static final String HOUR = "HOUR";
    public static final String MINUTE = "MINUTE";
    public static final String SECOND = "SECOND";

    /**
     * yyyyMMdd格式字符
     */
    public static final String yyyyMMdd = "yyyyMMdd";
    /**
     * yyyyMM格式字符
     */
    public static final String yyyyMM = "yyyyMM";

    /**
     * HHmmss格式字符
     */
    public static final String HHmmss = "HHmmss";

    /**
     * yyyyMMddHHmmss格式字符
     */
    public static final String MMddHHmmss = "yyyyMMddHHmmss";

    /**
     * yyyy-MM-dd格式字符
     */
    public static final String yyyy_MM_dd = "yyyy-MM-dd";
    
    /**
     * yyyy-MM-dd格式字符
     */
    public static final String yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";

    /**
     * HH:mm:ss格式字符
     */
    public static final String HH_mm_ss = "HH:mm:ss";

    /**
     * 利用时间差来记录时间<br>
     * 平台时间比本地时间快多少(可能为负),<br>
     * 若没设置则span = 0,认为本地时间就是平台时间
     */
    private static long span = 0;

    /**
     * 获取指定年月的第一天
     * @param year
     * @param month
     * @return
     */
    public static String getFirstDayOfMonth1(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最小天数
        int firstDay = cal.getMinimum(Calendar.DATE);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH,firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /**
     * 获取指定年月的最后一天
     * @param year
     * @param month
     * @return
     */
    public static String getLastDayOfMonth1(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }


    /**
     * 获取当前前一天的时间
     *
     */
    public static String getLastDay(){
        Date dNow = new Date();  //当前时间
        Date dBefore = new Date();
        Calendar calendar = Calendar.getInstance();   //得到日历
        calendar.setTime(dNow);//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
        dBefore = calendar.getTime();  //得到前一天的时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
        String defaultStartDate = sdf.format(dBefore); //格式化前一天
        String defaultEndDate = sdf.format(dNow); //格式化当前时间
        System.out.println("前一天的时间是：" + defaultStartDate);
        return defaultStartDate;
    }

    /**
     * 取当前时间
     * 
     * @return
     * @Author:Junjie.Lai lai_jj@hisuntech.com
     * @Since:2013-6-20
     * @Version:MCA2
     */
    public static Date getDate() {
        Date nowAndroid = new Date();
        long nowPlant = nowAndroid.getTime() + span;

        Date nowPlantDate = new Date(nowPlant);

        return nowPlantDate;
    }

    public static Calendar getCalendar() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getDate());
        return cal;
    }

    /**
     * 根据format串返回当前日期串
     * 
     * @param fomatString
     * @return
     * @Author:Junjie.Lai lai_jj@hisuntech.com
     * @Since:2013-6-24
     * @Version:Common
     */
    public static String getDateByFormatStr(String fomatString) {
        Date date = getDate();
        SimpleDateFormat df = new SimpleDateFormat(fomatString);
        return df.format(date);
    }
    
    /**
     * 根据当前日期串串返回format
     * 
     * @param fomatString
     * @return
     * @Author:Junjie.Lai lai_jj@hisuntech.com
     * @Since:2013-6-24
     * @Version:Common
     */
    public static Date getStrByFormatDate(String Str, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Date date = null;
        try {
			 date = df.parse(Str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        return date;
    }
    
    /**
     * 获取指定日期时间的增加偏移量后格式化的字符串
     * 
     * @param minute
     *            分钟偏移量
     * @return 格式化的日期时间字符串
     */
    public static String getDateStringByMinuteOffset(int value) {
        Calendar calendar = getCalendar();
        calendar.add(Calendar.MINUTE, value);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(calendar.getTime());
    }
    
    
    /**
     * 获取指定日期时间的增加偏移量后格式化的字符串
     * 
     * @param YEAR
     *            分钟偏移量
     * @return 格式化的日期时间字符串
     */
    public static String getDateStringByYEAROffset(int value) {
        Calendar calendar = getCalendar();
        calendar.add(Calendar.YEAR, value);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(calendar.getTime());
    }
    /**
     * Title: convertDateToString<br/>
     * Description: 把data转为制定格式的字符串<br/>
     * 
     * @author lai_jj
     * @date 2014年12月17日下午3:31:14
     * 
     * @param date
     * @param format
     * @return
     */
    public static String convertDateToString(Date date, String format) {
        if (date == null) {
            return null;
        }
        if (format == null) {
            format = "yyyyMMddHHmmss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String result = sdf.format(date);
        return result;
    }


    
    
    /**
     * Title: convertDateToString<br/>
     * Description: 把data转为制定格式的字符串<br/>
     * 
     * @author lai_jj
     * @date 2014年12月17日下午3:31:14
     * 
     * @param date
     * @param format
     * @return
     */
    public static String convertDateToStr(Date date , String format) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String result = sdf.format(date);
        return result;
    }

    /**
     * 根据long类型的时间转出format的时间
     * 
     * @param timeLongVal
     * @param descFormat
     * @return
     * @Author:Junjie.Lai lai_jj@hisuntech.com
     * @Since:2013-6-25
     * @Version:Common
     */
    public static String formatDateLongToString(Long timeLongVal,
            String descFormat) {
        Date date = new Date(timeLongVal);
        SimpleDateFormat df = new SimpleDateFormat(descFormat);
        return df.format(date);
    }

    /**
     * 
     * Title: convertFormatDataToString<br/>
     * Description: 从yyyy-MM-dd HH:mm:ss 格式的时间里面取出 ddHHmmss<br/>
     * 
     * @author lai_jj
     * @date 2014年12月17日下午3:39:45
     * 
     * @param date
     * @return
     */
    public String convertFormatDataToString(String date) {
        String[] datesplite = date.split(" ");
        String[] before = datesplite[0].split("-");
        String[] after = datesplite[1].split(":");

        StringBuilder builder = new StringBuilder();
        builder.append(before[2]).append(after[0]).append(after[1])
                .append(after[2]);
        return builder.toString();
    }

    /**
     * 
     * Title: convertStringDateToFormatString<br/>
     * Description: 时间字段转换<br/>
     * 
     * @author lai_jj
     * @date 2014年12月25日下午3:14:16
     * 
     * @param srcDateStr
     *            源时间字符
     * @param srcFormat
     *            源时间格式
     * @param descFormat
     *            目标时间格式
     * @return
     */
    public static String convertStringDateToFormatString(String srcDateStr,
            String srcFormat, String descFormat) {
        if (srcDateStr == null || "".equals(srcDateStr)) {
            return "";
        } else {
            long longTime = formatDateStringToLong(srcDateStr, srcFormat);
            return formatDateLongToString(longTime, descFormat);
        }
    }

    /**
     * 将formatStr的时间 转成 long
     * 
     * @param date
     * @return
     */
    public static Long formatDateStringToLong(String date, String formatStr) {
        SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
        try {
            formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            return formatter.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0l;
    }

    /**
     * 计算时间间隔
     * 
     * @param lastEndTime
     *            上一次结束时间
     * @param currentBeginTime
     *            这一次开始时间
     * @param timeFormatStr
     *            时间格式
     * @return
     * @Author:Junjie.Lai bpascal.cn@gmail.com
     * @Since:2013-2-24
     * @Version:Digi Portal Demo
     */
    public static long getIntervalSecond(String lastEndTime, String currentBeginTime,
            String timeFormatStr) {
        long dlast, dbegin, dInterval;
        SimpleDateFormat df = new SimpleDateFormat(timeFormatStr);
        try {
            dlast = df.parse(lastEndTime).getTime();
            dbegin = df.parse(currentBeginTime).getTime();
            dInterval = Math.abs((dbegin - dlast) / 1000);// 时间间隔
        } catch (Exception e) {
            dInterval = 0;
            e.printStackTrace();
        }
        return dInterval;
    }

    /**
     * 根据秒数，计算时间
     * 
     * @param time
     * @return
     * @Author:Junjie.Lai bpascal.cn@gmail.com
     * @Since:2013-2-25
     * @Version:Digi Portal Demo
     */
    public String computSecond(long time) {
        long minute = time % 3600 / 60;// 分
        long second = time % 60;// 秒
        return String.valueOf((minute < 10 ? ("0" + minute) : minute) + ":"
                + (second < 10 ? ("0" + second) : second));
    }

    /**
     * 根据秒数，计算时间
     * 
     * @param time
     * @return
     * @Author:Junjie.Lai bpascal.cn@gmail.com
     * @Since:2013-2-25
     * @Version:Digi Portal Demo
     */
    public String computSecondToFullTime(long time) {
        long hour = time / 3600;// 时
        long minute = time % 3600 / 60;// 分
        long second = time % 60;// 秒
        return String.valueOf((hour < 10 ? ("0" + hour) : hour) + ":"
                + (minute < 10 ? ("0" + minute) : minute) + ":"
                + (second < 10 ? ("0" + second) : second));
    }

    /**
     * 对日期进行计算
     * 
     * @param date
     *            日期
     * @param unit
     *            计算单位
     * @param offset
     *            偏移量
     * @return
     */
    public static String calculateDate(String date, String unit, int offset) {
        // 设置日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        Date beginDt = null;
        try {
            beginDt = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 设置计算方式
        int type;
        if (unit.equals(DateUtil.YEAR)) {
            type = Calendar.YEAR;
        } else if (unit.equals(DateUtil.MONTH)) {
            type = Calendar.MONTH;
        } else if (unit.equals(DateUtil.DAY)) {
            type = Calendar.DAY_OF_YEAR;
        } else {
            return "";
        }

        // 计算日期
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(beginDt);
        rightNow.add(type, offset);

        Date endDt = rightNow.getTime();
        String reStr = sdf.format(endDt);
        return reStr;
    }

    /**
     * 
     * Title: calculateTime<br/>
     * Description: 对时间进行计算<br/>
     * 
     * @author gaopeng
     * @date 2014年12月22日下午4:44:41
     * 
     * @param time
     *            时间
     * @param unit
     *            单位
     * @param offset
     *            偏移量
     * @return
     */
    public static String calculateTime(String time, String unit, int offset) {
        // 设置日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");

        Date beginTm = null;
        try {
            beginTm = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 设置计算方式
        int type;
        if (unit.equals(DateUtil.HOUR)) {
            type = Calendar.HOUR_OF_DAY;
        } else if (unit.equals(DateUtil.MINUTE)) {
            type = Calendar.MINUTE;
        } else if (unit.equals(DateUtil.SECOND)) {
            type = Calendar.SECOND;
        } else {
            return "";
        }

        // 计算日期
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(beginTm);
        rightNow.add(type, offset);

        Date endTm = rightNow.getTime();
        String reStr = sdf.format(endTm);
        return reStr;
    }

    /**
     * 
     * Title: calculateDateTime<br/>
     * Description: 日期时间计算 <br/>
     * 
     * @author gaopeng
     * @date 2014年12月22日下午4:53:10
     * 
     * @param dateTime
     * @param unit
     * @param offset
     * @return
     */
    public static String calculateDateTime(String dateTime, String unit,
            int offset) {
        // 设置日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

        Date beginTm = null;
        try {
            beginTm = sdf.parse(dateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 设置计算方式
        int type;
        if (unit.equals(DateUtil.HOUR)) {
            type = Calendar.HOUR_OF_DAY;
        } else if (unit.equals(DateUtil.MINUTE)) {
            type = Calendar.MINUTE;
        } else if (unit.equals(DateUtil.SECOND)) {
            type = Calendar.SECOND;
        } else if (unit.equals(DateUtil.HOUR)) {
            type = Calendar.HOUR_OF_DAY;
        } else if (unit.equals(DateUtil.MINUTE)) {
            type = Calendar.MINUTE;
        } else if (unit.equals(DateUtil.SECOND)) {
            type = Calendar.SECOND;
        } else {
            return "";
        }

        // 计算日期
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(beginTm);
        rightNow.add(type, offset);

        Date endTm = rightNow.getTime();
        String reStr = sdf.format(endTm);
        return reStr;
    }
    
    /**
     *计算两个日期之间相差的天数 
     * @throws ParseException 
     */
    public static int calBetweenDays(String date1,String date2) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        
        Calendar cal = Calendar.getInstance();
        Date d1 = sdf.parse(date1);
        Date d2 = sdf.parse(date2);
        
        cal.setTime(d1);
        long t1 = cal.getTimeInMillis();
        cal.setTime(d2);
        long t2 = cal.getTimeInMillis();
        long days = (t2-t1)/(1000*3600*24);
        int a = (int) days;
        return a;
    }
    
    /**
     *计算两个日期之间相差的月数
     * @throws ParseException 
     */
    public static int calBetweenMonths(String date1,String date2) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        
        Calendar cal = Calendar.getInstance();
        Date d1 = sdf.parse(date1);
        Date d2 = sdf.parse(date2);
        
        cal.setTime(d1);
        int m1 = cal.get(Calendar.MONTH);
        int y1 = cal.get(Calendar.YEAR);
        cal.setTime(d2);
        int y2 = cal.get(Calendar.YEAR);
        int m2 = cal.get(Calendar.MONTH);
        if(y2<y1){
        	return -1;
        }else if(y2 == y1){
        	return m2 - m1 ;
        }else{
        	return (y2-y1)*12 + m2 -m1;
        }
        
    } 
    
    
    public static String   dateAdd(String time,int monNum) throws ParseException {
		 SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		  Date date = dateformat.parse(time);
		     Calendar   calendar   =   new   GregorianCalendar(); 
		     calendar.setTime(date); 
		     calendar.add(calendar.MONTH, monNum);//把日期往后增加一个月.整数往后推,负数往前移动
		     date=calendar.getTime();   //这个时间就是日期往后推一天的结果 
		     String   datetime =  dateformat.format(date);
		return datetime;
		
	}
    
    
    public static void main(String args[]) throws ParseException{
//    	String date1 = "2015-11-01";
//    	String date2 = "2016-03-01";
//    	System.out.println(calBetweenMonths(date1, date2));
//    	int i = Integer.valueOf(DateUtil.getDateByFormatStr(DateUtil.yyyyMMdd));
    	
    	System.out.println(getDateStringByYEAROffset(1));
    	
    }
    
    public static  int calLastedTime(Date startDate) {
    	  long a = new Date().getTime();
    	  long b = startDate.getTime();
    	  int c = (int)((a - b) / 1000);
    	  return c;
    }
    
    /**
	 * 获取YYYYMMDD格式
	 * @return
	 */
	public static String getDays(){
		return new SimpleDateFormat(MMddHHmmss).format(new Date());
	}


    /**
     * 获取指定日期时间的增加偏移量后格式化的字符串
     *
     * @param value
     *            日偏移量
     * @return 格式化的日期时间字符串
     */
    public static String getDateStringByDayOffset(int value) {
        Calendar calendar = getCalendar();
        calendar.add(Calendar.DATE, value);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(calendar.getTime());
    }

    /**
     * 加天数后的日期
     * @param date
     * @param days
     * @return
     */
    public static String getAddDayDateStr(Date date, int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_YEAR, days);
        Date newDate = calendar.getTime();
        return convertDateToString(newDate,yyyy_MM_dd);
    }

    /**
     * 加天数后的日期
     * @param date
     * @param days
     * @return
     */
    public static Date getAddDayDate(Date date, int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_YEAR, days);
        return calendar.getTime();
    }
}
